package com.limou.service.impl;

import com.limou.mapper.OrderMapper;
import com.limou.mapper.ProductMapper;
import com.limou.pojo.Order;
import com.limou.pojo.OrderProduct;
import com.limou.pojo.Product;
import com.limou.pojo.User;
import com.limou.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<Order> selectAll() {
        return orderMapper.selectAll ();
    }

    @Override
    public List<Order> selectOfStatusAll(Order order) {
        return orderMapper.selectOfStatusAll (order);
    }

    @Override
    public Order selectOne(Order order) {
        return orderMapper.selectOne (order);
    }

    @Override
    public void updateOrder0(Order order) {
        orderMapper.updateOrder (order);
    }

    @Override
    public List<User> selectAllUser() {
        return orderMapper.selectAllUser ();
    }

    @Override
    public double totalMoney(List<Product> products) {
        double moneys = 0;
        for (Product product : products) {
            moneys += product.getPrice ()*product.getStock ();
        }
        return moneys;
    }

    @Override
    public void insertOrder(Order order) {
        orderMapper.insertOrder (order);
    }

    @Override
    public int selectNewId() {
        return orderMapper.selectNewId ();
    }

    @Override
    public void insertOrderProduct(int id,List<Product> products) {
        for (Product product:products) {
            if (product.getStock () == null) {
                product.setStock (1);
            }
            OrderProduct op = new OrderProduct ();
            op.setOrderID (id);
            op.setProductID (product.getId ());

            op = orderMapper.selectOrderProductOne (op);

            if (op == null) {
                OrderProduct orderProduct = new OrderProduct (id,product.getId (),product.getStock ());
                orderMapper.insertOrderProduct (orderProduct);
            } else {
                int num = op.getNumbers () + product.getStock ();
                op.setNumbers (num);
                orderMapper.updateOrderProduct(op);
            }
        }
    }

    @Override
    public void updateProductStack(List<Product> products) {
        for (Product product : products) {
            Product product1 = productMapper.queryProductById (product.getId ());
            int stock = product1.getStock () - product.getStock ();
            product1.setStock (stock);
            productMapper.updateProduct (product1);
        }
    }
}
